package com.yc.utils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yc.entities.BloodSugarPermission;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author kukaha
 * @version 1.0.0
 * @ClassName TreeToolUtils.java
 * @Description TODO
 * @createTime 2021年04月11日 12:39:00
 */
public class TreeToolUtils {

    /**
     * 根节点对象存放到这里
     *
     * @author kukaha
     */
    private List<BloodSugarPermission> rootList;
    /**
     * 其他节点存放到这里，可以包含根节点
     *
     * @author kukaha
     */
    private List<BloodSugarPermission> bodyList;

    public TreeToolUtils(List<BloodSugarPermission> rootList, List<BloodSugarPermission> bodyList) {
        this.bodyList = bodyList;
        this.rootList = rootList;
    }

    public List<BloodSugarPermission> getTree() {   //调用的方法入口
//        rootList = rootList.stream().sorted(Comparator.comparing(BloodSugarPermission::getPerOrder)).collect(Collectors.toList());
        if (bodyList != null && !bodyList.isEmpty()) {
            //声明一个map，用来过滤已操作过的数据
            Map<Integer, Integer> map = Maps.newHashMapWithExpectedSize(bodyList.size());
            rootList.forEach(r1->{
                Map<String,Object> objectMap = Maps.newHashMapWithExpectedSize(rootList.size());
                objectMap.put("title",r1.getTitle());
                objectMap.put("icon",r1.getIcon());
                objectMap.put("activeMenu",r1.getActiveMenu());
                r1.setMeta(objectMap);
            });
            //传递根对象和一个空map
            rootList.forEach(beanTree -> getChild(beanTree, map));
            return rootList;
        }
        return rootList;
    }

    public void getChild(BloodSugarPermission beanTree, Map<Integer, Integer> map) {
        List<BloodSugarPermission> childList = Lists.newArrayList();
        bodyList.stream()
                //map内不包含子节点的code
                .filter(c -> !map.containsKey(c.getId()))
                //子节点的父id==根节点的id 继续循环
                .filter(c -> c.getParentId().equals(beanTree.getId()))
                .forEach(c -> {
                    //当前节点code和父节点id
                    map.put(c.getId(), c.getParentId());
                    getChild(c, map);//递归调用
                    Map<String ,Object> objectMap = new HashMap<>();
                    objectMap.put("title",c.getTitle());
                    objectMap.put("icon",c.getIcon());
                    objectMap.put("activeMenu",c.getActiveMenu());
                    c.setMeta(objectMap);
                    childList.add(c);
                });
//        bodyList = bodyList.stream().sorted(Comparator.comparing(BloodSugarPermission::getPerOrder)).collect(Collectors.toList());
        beanTree.setChildren(childList);
    }
}